
# -*- coding: utf-8 -*-

import zbar
import hashlib
from PIL import Image
from Webservices import getNameByUserIdFromWebService
from config.Config import USER_WEBSERVICE_LIST

class QRPredictor():
	@staticmethod
	def predict(cv_image):
		scanner = zbar.ImageScanner()
		scanner.parse_config('enable')

		pil = Image.fromarray(cv_image).convert('L')
		width, height = pil.size
		raw = pil.tostring()
		image = zbar.Image(width, height, 'Y800', raw)

		scanner.scan(image)

		res = {"type": None, "data": None}
		for symbol in image:
			res["type"] = symbol.type
			res["data"] = unicode(symbol.data)
			break

		del image

		if USER_WEBSERVICE_LIST.has_key(res["data"]):
			result = {
				'qr': {
					'name': getNameByUserIdFromWebService(res["data"]),
					'username': unicode(res["data"]),
					'hash': hashlib.md5("$$%s##" % unicode(res["data"])).hexdigest(),
					'type': unicode(res["type"])
				}
			}
			return result
		return None
